﻿
using System;
using System.Collections.Generic;
using FacebookXmpp.Parse;

namespace FacebookXmpp.Stanzas
{
	internal class Roster : Stanza
	{
		public Roster()
		{
			NextResponse = String.Format( @"<iq id=""{0}"" type=""get""><query xmlns=""jabber:iq:roster"" /></iq>", NextId );
		}

		internal override StanzaListenCriteria ListenFor
		{
			get { return new StanzaListenCriteria( "iq", "query", false, StanzaListenCriteria.DefaultResponseTimeMilliseconds * 4); }
		}

        public override void ProcessResponse(MessageData recieved)
		{
			Stream.RemoveHandler( this );
			
			List<MessageData> people = recieved.Path( "query/item" ) as List<MessageData>;
			if (people == null)
				return;

			foreach (var person in people)
            {
                Person peep = new Person(Stream.Dashboard) { Name = person.Attributes["name"], Id = person.Attributes["jid"] };
                
                if(Stream.Dashboard.Online.Contains(peep.Id))
                    peep.State = Status.Available;

                if (person.HasChildren)
                {
                    foreach (var group in person.GetChildren())
                    {
                        if (group.Name == "group")
                        {
                            peep.Groups.Add((string)group.Value);
                            if (Stream.Dashboard.Groups.Contains((string)group.Value) == false)
                            {
                                Stream.Dashboard.Groups.Add((string)group.Value);
                            }
                        }
                    }
                }

                Stream.Dashboard.Friends.Add(peep);
            }            
		}
	}
}
